//
//  LXRMeFooterView.m
//  01- 百思不得姐
//
//  Created by mac on 16/6/30.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "LXRMeFooterView.h"
#import "LXRSquareModel.h"
#import "LXRSquareButton.h"
#import "LXRWebViewController.h"


#import "AFNetworking.h"
#import "MJExtension.h"
#import "UIButton+WebCache.h"
@implementation LXRMeFooterView
-(instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        //清空背景颜色
        self.backgroundColor = [UIColor clearColor];
        //参数
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        params[@"a"] = @"square";
        params[@"c"] = @"topic";
        LXRWeakSelf;
        // 发送请求
       [[AFHTTPSessionManager manager] GET:@"http://api.budejie.com/api/api_open.php" parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
           
                NSArray *sqaure = [LXRSquareModel mj_objectArrayWithKeyValuesArray:responseObject[@"square_list"]];

                // 创建方块
                [weakSelf createSquares:sqaure];
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
            }];
    }
    return self;
}

-(void)createSquares:(NSArray*)sqaure{
    // 一行最多4列
    int maxCols = 5;
    // 宽度和高度
    CGFloat buttonW = LXRScreenW / maxCols;
    CGFloat buttonH = buttonW;
    for (int i = 0; i<sqaure.count; i++) {

        // 创建按钮
        LXRSquareButton *button = [LXRSquareButton buttonWithType:UIButtonTypeCustom];
        // 监听点击
        [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        // 传递模型
        button.square = sqaure[i];
        [self addSubview:button];
        // 计算frame
        int col = i % maxCols;
        int row = i / maxCols;
        button.x = col * buttonW;
        button.y = row * buttonH;
        button.width = buttonW;
        button.height = buttonH;
    }
    // 万能公式计算总页数 == (总个数 + 每页的最大数 - 1) / 每页最大数
    NSUInteger rows = (sqaure.count + maxCols - 1) / maxCols;
    // 计算footer的高度
    self.height = rows * buttonH;
    // 重绘
    [self setNeedsDisplay];
    
}

-(void)buttonClick:(LXRSquareButton*)button{
    //如果网址不是http开头就返回
    if (![button.square.url hasPrefix:@"http"]) return;

    LXRWebViewController* web = [[LXRWebViewController alloc]init];
    web.url = button.square.url;
    
    // 取出当前的导航控制器
    UITabBarController *tabBarVc = (UITabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    UINavigationController *nav = (UINavigationController *)tabBarVc.selectedViewController;
    [nav pushViewController:web animated:YES];
    
                                  
    
    
}
/**设置背景图片*/
//-(void)drawRect:(CGRect)rect{
//    [[UIImage imageNamed:@"mainCellBackground"] drawInRect:rect];
//}
@end
